package de.jeeyeon;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import de.jeeyeon.util.DateProvider;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.Toast;

public class CalendarActivity extends Activity 
{
	
	private CalendarView calendar;	
	private String author;
	private String date;
	
	private boolean firstStart = false;
	
	public static final String URL = "http://snuk87.sn.funpic.de/get_entrys.php";
	public static final String PREFS_NAME = "EntryFile";
	
	private String[] entrys;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);
		
		calendar = (CalendarView) findViewById(R.id.calendarView1);
		
		Bundle extras = getIntent().getExtras();
		author = extras.getString("author");
		
		Calendar cal = Calendar.getInstance();
		
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.MONTH, 2);
		cal.set(Calendar.YEAR, 2014);

		
		calendar.setMinDate(cal.getTimeInMillis());
		calendar.setMaxDate(System.currentTimeMillis() + (1000 * 60 * 60 * 8));
		
		calendar.setOnDateChangeListener(new OnDateChangeListener() 
		{
			
			@Override
			public void onSelectedDayChange(CalendarView view, int year, int month,
					int dayOfMonth) 
			{
				String day = null;
				String month_ = null;
					
				if(dayOfMonth < 10)
				{
					day = "0" + dayOfMonth;
				}
				else{
					day = Integer.toString(dayOfMonth);
				}
				
				if(month < 10)
				{
					month_ = "0" + (month + 1);
				}
				else{
					month_ = Integer.toString(month);
				}
				
				
				date = day + "-" + month_ + "-" + year;
				
				if(firstStart)
				{
					//load caching
					
					Set<String> set = new LinkedHashSet<String>();
					
					SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
					set = settings.getStringSet(date, new LinkedHashSet<String>());
					
					if(!set.isEmpty() && set != null)
					{
						
						entrys = new String[set.size()];
						set.toArray(entrys);
						
						Intent i = new Intent(CalendarActivity.this, EntryActivity.class);
						i.putExtra("date", date);
						i.putExtra("entrys", entrys);
						startActivity(i);	
					}
					else
					{
						getEntrys();
					}
					
					//load end
				}
				else
				{
					firstStart = true;
				}			
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.calendar, menu);
		return true;
	}
	
	private void getEntrys()
	{
		new AsyncTask<Void, Void, String>() 
		{
			@Override
			protected String doInBackground(Void... params) 
			{
				String output = null;
				try
				{		
					DefaultHttpClient client = new DefaultHttpClient();
					HttpPost post = new HttpPost(URL);
					
			        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			        nameValuePairs.add(new BasicNameValuePair("date", date));
			        nameValuePairs.add(new BasicNameValuePair("author", author));
			        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					
					HttpResponse httpResponse = client.execute(post);

					HttpEntity httpEntity = httpResponse.getEntity();
					output = EntityUtils.toString(httpEntity).trim();
					
					int index = output.indexOf("<!");
					
					output = output.substring(0, index);
				}
				catch(Exception e){ e.printStackTrace(); Log.d("Catch: " + e.toString(), "jeejee"); }
				
				return output;
			}
			
			protected void onPostExecute(String result)
			{	
				int index = result.indexOf("----");
				int count = Integer.parseInt(result.substring(0, index));
				
				result = result.substring(index + 4);
				if(count > 0)
				{				
					entrys = new String[count];
					
					entrys = result.split("----");
					
					//save for caching
					
					if(date.equals(DateProvider.getDate()) || date.equals(DateProvider.getDateFromYesterday()))
					{
						// dont save
					}
					else
					{
						SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
						SharedPreferences.Editor editor = settings.edit();
						
						Set<String> set = new LinkedHashSet<String>();
						
						for(int i = 0; i < entrys.length; i++)
						{
							set.add(entrys[i]);
						}
						editor.putStringSet(date, set);
						
						editor.commit();
					}
					//-----save end
					
					Intent i = new Intent(CalendarActivity.this, EntryActivity.class);
					i.putExtra("date", date);
					i.putExtra("entrys", entrys);
					startActivity(i);					
				}
				else
				{
					Toast.makeText(getApplicationContext(), "No entrys were found", Toast.LENGTH_LONG).show();
				}
			}
		}.execute();
	}
}
